package com.xxxx.car.appointment.utils;

import com.xxxx.car.appointment.annotation.isPhone;
import com.xxxx.car.common.utils.StringUtils;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

@Component
public class ValidateUtils implements ConstraintValidator<isPhone,String> {

    private boolean required = false;

    @Override
    public void initialize(isPhone constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String phone, ConstraintValidatorContext constraintValidatorContext) {
        if (required) {
            return Pattern.matches("^1[3-9]\\d{9}$", phone);
        } else {
            if (StringUtils.isEmpty(phone)) {
                return false;
            } else {
                return Pattern.matches("^1[3-9]\\d{9}$", phone);
            }
        }
    }
}
